package com.itheima.web.manager;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.Admin;
import com.itheima.service.db.AdminService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.web.exception.BusinessException;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PostMapping;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service // spring的
public class AdminManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminService adminService;

    public LineCaptcha genVerification(String uuid) {
        // 1.生成验证码
        LineCaptcha lineCaptcha = new LineCaptcha(300, 150);

        // 2.将验证码存入redis中
        String code = lineCaptcha.getCode();
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_CODE + uuid, code, Duration.ofMinutes(5));

        // 3.返回
        return lineCaptcha;
    }

    public String login(String username, String password, String verificationCode, String uuid) {
        // 1.对比验证码，根据uuid查询redis
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_CODE + uuid);
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            throw new BusinessException("验证码不匹配~~~");
        }
        // 2.调用rpc查询admin
        Admin admin = adminService.findByUsername(username);
        if (admin == null) {
            throw new BusinessException("此用户不存在~~~");
        }
        // 3.对比密码
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5, admin.getPassword())) {
            throw new BusinessException("密码不正确~~~");
        }
        // 4.登录成功
        // 4-1 清除redis
        stringRedisTemplate.delete(ConstantUtil.ADMIN_CODE + uuid);
        // 4-2 生成token
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        String token = JwtUtil.createToken(claims);
        // 4-3 redis续期
        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));
        //  5.返回token
        return token;
    }

    public Admin findAdminByToken(String token) {
        // 1.处理token，前端工程师有个习惯，会将token添加 Bearer xxxxx
        token = token.replaceAll("Bearer ", "");
        // 2.查询redis
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.ADMIN_TOKEN + token);
        if (StrUtil.isEmpty(json)) {
            return null;
        }
        // 3.将json转为admin
        Admin admin = null;
        try {
            admin = JSON.parseObject(json, Admin.class);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        // 4. redis续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.ADMIN_TOKEN + token, json, Duration.ofHours(1));
        // 5.返回admin
        return admin;
    }

    public void logout(String token) {
        // 1.处理token，前端工程师有个习惯，会将token添加 Bearer xxxxx
        token = token.replaceAll("Bearer ", "");
        // 2.删除redis中的token
        stringRedisTemplate.delete(ConstantUtil.ADMIN_TOKEN+token);
    }
}
